<script setup lang="ts">
import { reactive, ref, onBeforeMount, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/store'
import { ElMessage as message } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { getSuccessStatus, getLoginShortMessageCaptcha, loginByPhone, wxBindToUserAndLogin } from '@/api/login'

const props = defineProps<{
	wxBindKey: string
}>()

const emits = defineEmits(['update:wxBindKey'])

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const formState: { phone: string; verifyCode: string } = reactive({
	phone: '',
	verifyCode: '',
})

const isLoading = ref(false)
const formRef = ref<FormInstance>()
const time = ref(0)
let timer: any
let inputList: NodeListOf<HTMLElement>
const phoneReg = /^\d{11}$/

const rules = {
	phone: [
		{ required: true, message: '请输入你的手机号!', trigger: 'blur' },
		{ pattern: phoneReg, message: '请输入正确格式的手机号!', trigger: 'blur' },
	],
	verifyCode: [
		{ required: true, message: '请输入你的验证码!', trigger: 'blur' },
		{ pattern: /^\d{6}$/, message: '请输入6位数字的验证码!', trigger: 'blur' },
	],
}

onBeforeMount(() => {
	const { phone } = userStore.loginInfo
	if (phone) {
		formState.phone = phone
	}
})

onMounted(() => {
	inputList = document.querySelectorAll('.phone-form .el-input__inner')
})

const resetForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return
	formEl.resetFields()
}

const handleInputsKeyDown = (e: KeyboardEvent) => {
	if (e.key == 'ArrowUp' || e.key == 'ArrowDown') e.preventDefault()
}

const handleInputsKeyUp = (index: number, e: KeyboardEvent) => {
	if (e.key == 'Enter') submitForm(formRef.value)
	const toggleFocus = (direction: 'down' | 'up') => {
		let i: number
		if (direction == 'up') {
			i = index - 1
			if (i < 0) i = inputList.length - 1
		} else {
			i = index + 1
			if (i > inputList.length - 1) i = 0
		}
		inputList[i].focus()
	}
	if (e.key == 'ArrowUp') {
		toggleFocus('up')
	}
	if (e.key == 'ArrowDown') {
		toggleFocus('down')
	}
}

const bindSendVerifyCode = async () => {
	if (!formState.phone) {
		message.warning('请填写手机号！')
		return
	}
	if (!phoneReg.test(formState.phone)) {
		message.warning('请填写正确格式的手机号！')
		return
	}
	const res = await getLoginShortMessageCaptcha(formState.phone)
	console.log(res)
	if (res.code == getSuccessStatus() && res.data) {
		time.value = 120
		timer = setInterval(() => {
			if (time.value <= 0) {
				clearInterval(timer)
				timer = 0
				return
			}
			time.value--
		}, 1000)
	} else {
		message.warning('获取验证码失败！')
	}
}

const submitForm = async (formEl: FormInstance | undefined) => {
	if (isLoading.value) return
	//console.log(values)
	isLoading.value = true
	const { phone, verifyCode } = formState
	let res: any
	if (props.wxBindKey) res = await wxBindToUserAndLogin({ phone, shortMessageCode: verifyCode, wxBindKey: props.wxBindKey })
	else res = await loginByPhone({ phone, shortMessageCode: verifyCode })
	isLoading.value = false
	if (res.code == getSuccessStatus()) {
		await userStore.login(res.data.token)
		const { id } = userStore.loginInfo
		if (route.query.redirect && res.id === id)
			// 防止重定向到没有权限的页面
			router.push(decodeURIComponent(route.query.redirect as string))
		else router.push('/')
		userStore.$patch((s) => {
			s.loginInfo = { ...s.loginInfo, id: res.id, phone: formState.phone, activeTab: 'phone' }
		})
		emits('update:wxBindKey', '')
	}
}

const fail = (err: any) => {
	console.log('err', err)
}
</script>

<template>
	<el-form class="phone-form" ref="formRef" :model="formState" :rules="rules">
		<el-form-item prop="phone">
			<el-input v-model="formState.phone" placeholder="请输入手机号" prefix-icon="Iphone" clearable @keyup="handleInputsKeyUp(0, $event)" @keydown="handleInputsKeyDown"></el-input>
		</el-form-item>

		<el-form-item prop="verifyCode">
			<el-input
				v-model="formState.verifyCode"
				placeholder="请输入验证码"
				prefix-icon="Key"
				style="width: 60%; margin-right: 10px"
				clearable
				@keyup="handleInputsKeyUp(1, $event)"
				@keydown="handleInputsKeyDown"
			>
			</el-input>
			<el-button :disabled="!!time" @click="bindSendVerifyCode">获取验证码{{ `${time ? `(${time})` : ''}` }}</el-button>
		</el-form-item>

		<el-form-item>
			<el-button type="primary" @click="submitForm(formRef)" class="phone-form-button" style="margin-top: 10px" :loading="isLoading"> 登录 </el-button>
		</el-form-item>
	</el-form>
</template>

<style lang="scss" scoped>
.phone-form {
	.phone-form-button {
		width: 100%;
	}
}
</style>
